trigger OORSecondaryOwnerShareTrigger on Opportunity (after update,after insert) {
    
    List<Opportunity> OppList = new List<Opportunity>();
    List<OpportunityTeamMember> OpportunityTeamMemberList = new List<OpportunityTeamMember>();
    List<OpportunityTeamMember> OpportunityTeamMemberDelete = new List<OpportunityTeamMember>();
    Map<ID,User> userCheckMap= New Map<ID,User>();
    Set<Id> OpptyIds = new Set<Id>();
    Set<Id> OwenerSet = new Set<Id>();
    
    Set<String> oorOppRecrodTypeDevNames = new Set<String>{'SFA_OOR_Order','SFA_OOR_Renwals'};
    Set<Id> oorOppsToAccntShareId = new Set<Id>(); 
    Map<Id,RecordType> rtMap = new Map<Id,RecordType>();
    
    if(trigger.isUpdate)
    {
       rtMap = new Map<Id,RecordType>([SELECT Id, Name FROM RecordType 
                                       WHERE sObjectType = 'Opportunity' AND 
                                             DeveloperName IN :oorOppRecrodTypeDevNames]);
    }
    
    // UPdated new Condition for Primary owner in the Trigger.IsUpdate(MT)
        for(Opportunity opp:Trigger.new){
        
        if(Trigger.ISUPDATE){
		  if(!rtMap.isEmpty() && rtMap.containskey(opp.RecordTypeId))
          {
             if(opp.OwnerId != trigger.oldMap.get(opp.Id).OwnerId)
             {
                oorOppsToAccntShareId.add(opp.Id);
             }
          }               
		 
         if(opp.Opportunity_Type__c=='Digital Express' || opp.Opportunity_Type__c=='Bill Cycle Evergreen' || opp.Opportunity_Type__c=='Net Revenue'||opp.Opportunity_Type__c=='AF Assigned'){
                if(opp.Ext_Primary_Owner__c!=null && (opp.Ext_Primary_Owner__c!=Trigger.oldMap.get(opp.id).Ext_Primary_Owner__c)){        
                   OppList.add(opp);
                   OpptyIds.add(opp.id);
                  }
                 else if (opp.Ext_Primary_Owner__c==null && Trigger.oldMap.get(opp.id).Ext_Primary_Owner__c!=null){
                   OpptyIds.add(opp.id);
                  }
                if(opp.Ext_Secondary_Owner__c!=null && (opp.Ext_Secondary_Owner__c!=Trigger.oldMap.get(opp.id).Ext_Secondary_Owner__c)){        
                   OppList.add(opp);
                   OpptyIds.add(opp.id);
                  }
                 else if (opp.Ext_Secondary_Owner__c==null && Trigger.oldMap.get(opp.id).Ext_Secondary_Owner__c!=null){
                  OpptyIds.add(opp.id);
                 }
              }
          
          if(opp.Secondary_Owner__c!=null && (opp.Secondary_Owner__c!=Trigger.oldMap.get(opp.id).Secondary_Owner__c) ){
            
                OppList.add(opp);
                OpptyIds.add(opp.id);
            
            }
            else if(opp.Secondary_Owner__c==null && Trigger.oldMap.get(opp.id).Secondary_Owner__c != null ){
                OpptyIds.add(opp.id);
            }
          }
         else{
         if(opp.Secondary_Owner__c!=null){
         OppList.add(opp);
         OpptyIds.add(opp.id);
         }
         if(opp.Opportunity_Type__c=='Digital Express' || opp.Opportunity_Type__c=='Bill Cycle Evergreen' || opp.Opportunity_Type__c=='Net Revenue'||opp.Opportunity_Type__c=='AF Assigned'){
              if (opp.Ext_Primary_Owner__c!=null){
              OppList.add(opp);
              OpptyIds.add(opp.id);
              }
              if (opp.Ext_Secondary_Owner__c!=null){
              OppList.add(opp);
              OpptyIds.add(opp.id);
              }
           }

         }
        }
         for(User singleuser:[Select Id from User where SFA_Office__c != NULL and ISACTIVE=TRUE]){ 
         userCheckMap.put(singleuser.Id,singleuser);  
         }
         OwenerSet = userCheckMap.KeySet();
         //System.debug('OWNERSETtest'+OwnerSet);
         System.Debug('MAPTEST'+userCheckMap);  
         for(integer i=0;i<OppList.size();i++){
             OpportunityTeamMember OppMemb = new OpportunityTeamMember();
             OppMemb.OpportunityId = OppList[i].id;
             // Adding Secondary Owner to Sharing Logic 
             OppMemb.UserId = OppList[i].Secondary_Owner__c;
             if(OppMemb.UserId!=null){
                if(OwenerSet.Contains(OppMemb.UserId)){
                   OpportunityTeamMemberList.add(OppMemb);
                     } 
                }
             
             OpportunityTeamMember OppPrimaryMemb = new OpportunityTeamMember();
             OppPrimaryMemb.OpportunityId = OppList[i].id;
             //Adding Primary  owner to Sharing Logic for Order Type='Bill Evergreen' OR Order Type='Digital Express' OR  Order Type= 'Net Revenue' OR Order Type= 'AF Assigned'(MT)
             oppPrimaryMemb.UserId=OppList[i].Ext_Primary_Owner__c;
             
             OpportunityTeamMemberList.add(OppPrimaryMemb);
             
             OpportunityTeamMember OppSecondaryMemb = new OpportunityTeamMember();
             OppSecondaryMemb.OpportunityId = OppList[i].id;
             //Adding Secondary  owner to Sharing Logic for Order Type='Bill Evergreen' OR Order Type='Digital Express' OR  Order Type= 'Net Revenue' OR Order Type= 'AF Assigned'(MT)
             OppSecondaryMemb.UserId=OppList[i].Ext_Secondary_Owner__c;
             if(OppSecondaryMemb.UserId!=null){
                 if(OwenerSet.Contains(OppSecondaryMemb.UserId)){ 
                      OpportunityTeamMemberList.add(OppSecondaryMemb);
                      }
               }
             
             }
    
       
           if(OpptyIds.size()>0){
              try{
               OpportunityTeamMemberDelete = [select id from OpportunityTeamMember where OpportunityId IN: OpptyIds];
                  if(OpportunityTeamMemberDelete.size()>0){
                       delete OpportunityTeamMemberDelete;
                   }
               }
               Catch(System.DmlException e){
                   for (Integer i = 0; i < e.getNumDml(); i++) {
                       System.debug(e.getDmlMessage(i));
                   }
               }
           }
           if(OpportunityTeamMemberList.size()>0){
               try{
                   Insert OpportunityTeamMemberList;
               }
               catch (System.DmlException e) {
                for (Integer i = 0; i < e.getNumDml(); i++) {
                  System.debug(e.getDmlMessage(i));
                }   
              }
           }
           
           if(!oorOppsToAccntShareId.isEmpty())
           {
                 List<OpportunityShare> oorOppShareList = new List<OpportunityShare>();
                 List<Opportunity> oorOppsShareToAccntList = [SELECT Id, Name, OwnerId, Account.OwnerId FROM Opportunity WHERE Id IN :oorOppsToAccntShareId];
                 for(Opportunity opp : oorOppsShareToAccntList)
                 {
                    if(opp.OwnerId != opp.Account.OwnerId)
                    {
                                   OpportunityShare os = new OpportunityShare();
                                   os.OpportunityAccessLevel = 'Read';
                                   os.UserOrGroupId = opp.Account.OwnerId;
                                   os.OpportunityId = opp.Id;
                                   oorOppShareList.add(os);
                    }
                 } 
                 insert oorOppShareList;
           }
           
       
      }